<template>
    <view class="rx-button-edit" v-if="!readOnly">
            <rx-boxs v-model="curVal" @select="showDialog" @buttonSelect="buttonSelect" :read-only="readOnly"
                     :single="single" :icon="icon" :type="'btnEdit'" buttonedit="true"></rx-boxs>
    </view>
    <template v-else-if="metadata.options.link">
        <a class="rx-button-link" @click="linkClick" >{{ getValue(this.curVal)}}</a>
    </template>
    <view v-else class="rx-disabled">
        {{ getValue(this.curVal) }}
    </view>
</template>

<script>
/**
 * 编辑型按钮
 */
import MForm from "../js/MForm";
import RxBoxs from "../../form/common/RxBoxs.vue";
import FormBoListPreview from "../../form/formBoList/FormBoListPreview.vue";
import Dialog from "@/js/Dialog.js";
import baseButtonFunc from "@/js/baseButtonFunc.js"
import CustomQuery from "@/views/modules/form/customForm/js/CustomQuery.js";
import LinkUrl from "@/js/LinkUrl"
export default {
    name: "MButtonEdit",
    mixins: [MForm,baseButtonFunc,LinkUrl],
    components: {
        RxBoxs,
        FormBoListPreview
    },
    data() {
        return {
            confJson: {},
            returnFields: {},
            isMain: true,
            gridName: "",
            defaultVal: "",
            single: true,
            curVal: "",
            icon:'',
        }

    },
    created() {
        if (this.metadata.options.mode == 'dialog' && this.metadata.options.eventConfig) {
            let dialogConfig = JSON.parse(this.metadata.options.eventConfig);
            this.single = dialogConfig.singleType == 'single' ? true : false;
        }
        this.icon = this.metadata.options.checkedChildren?this.metadata.options.checkedChildren:'';
        this.initValue(this.value);
    },
    methods: {
        i18n(name, text, key) {
            return this.$ti18(name, text, "formLang", key);
        },
        getValue(value) {
            if (value) {
                let val = new Function("return " + value)();
                return val.label;
            }
            return ''
        },
        //判断是否要清空子表
        buttonSelect(idx) {
            this.curVal = idx;
            this.setData(this.curVal);
        },
        //打开对话框。
        showDialog() {
            if (this.metadata.options.mode == 'method') {
                //自定义方法
                var parent = this.formVm;
                parent[this.metadata.options.eventConfig](this.globalData, this.curVal)
            } else {
                let binding = JSON.parse(this.metadata.options.eventConfig);
                if(binding.beforeMethod && this.isBeforeMethod(binding.beforeMethod)){
                    return;
                }

                //对话框
                if (!binding || !binding.dialogAlias || !JSON.parse(binding.dialogAlias).value) {
                    uni.showToast({
                        title: this.i18n('boundDialog', '没有绑定对话框'), // 消息内容
                        duration: 1500, // 持续时间（单位：毫秒）
                        icon: 'none' // 图标类型（可选值：success/loading/none）
                    });
                    return;
                }
                var dialogAlias = JSON.parse(binding.dialogAlias).value;
                var gridInput = binding.gridInput;
                /*如果输入条件有必填，则提示*/
                if(this.isConditionRequired(gridInput,this.formVm.data,this.data)){
                    return;
                }

                //构建查询条件。
                var params = CustomQuery.getParamsInput(gridInput,this.globalData,this.data,this.formVm);
                params = Object.keys(params).map(function (key) {
                    return key + "=" + params[key];
                }).join("&");
                let self_ = this;
                let initData = this.getInitData();
                let conf = {
                    data: {
                        alias: dialogAlias,
                        pmtAlias: binding.pmtAlias,
                        single: this.single,
                        params: params,
                    },
                    curVm: this,
                };
                if (initData) {
                    conf.data.initData = initData;
                }
                Dialog.openDialog(conf, function (data) {
                    if (data.action == "ok") {
                        let eventConfig = JSON.parse(self_.metadata.options.eventConfig);
                        //绑定映射行
                        self_.bindRows(eventConfig, data.data.rows);
                        self_.handBindSelf(eventConfig, data.data.rows);
                        if (eventConfig.callback) {
                            self_.formVm[eventConfig.callback]({rows: data.data.rows});
                        }
                    }
                })
            }
        },
        /**
         * 获取初始化数据
         */
        getInitData() {
            if (!this.curVal) {
                return null;
            }
            let json = JSON.parse(this.curVal);
            if (!json.value) {
                return null;
            }
            let binding = JSON.parse(this.metadata.options.eventConfig);
            let valueField = binding.valueField;
            return {
                keyField: valueField,
                selected: json.value.split(",")
            }
        },
        /**
         * 绑定当前控件
         * @param binding
         * @param rows
         */
        handBindSelf(binding, rows) {
            let textField = binding.useCondSql == 'WEBREQ' || binding.useCondSql == 'INTERFACE' ? binding.textField : binding.textField.toUpperCase();
            let valueField = binding.useCondSql == 'WEBREQ' || binding.useCondSql == 'INTERFACE' ? binding.valueField : binding.valueField.toUpperCase();
            let aryText = [];
            let aryValue = [];
            for (let i = 0, j = rows.length; i < j; i++) {
                let row = rows[i];
                let value = row[valueField];
                let text = this.getText(row[textField]);
                aryValue.push(value);
                aryText.push(text);
            }
            let newVal = {label: aryText.join(","), value: aryValue.join(",")};
            this.curVal = JSON.stringify(newVal);
            this.setData(this.curVal)
        },
        initValue(val) {
            if (!val) return;
            if (val.indexOf("value") > -1) {
                this.curVal = val;
            } else { //单值情况
                this.curVal = JSON.stringify({
                    value: val,
                    label: val
                });
            }
        }
    },
    watch: {

        value: {
            handler(val, oldVal) {
                if (val) {
                    this.initValue(val);
                    if (val.indexOf("value") > -1) {
                        this.curvalue = val;
                    } else { //单值情况
                        this.curvalue = JSON.stringify({
                            value: val,
                            label: val
                        });
                    }
                } else {
                    this.curVal = '';
                }
            },
            deep: true
        }
    }
}
</script>

<style scoped>
.rx-button-link{
    color: #0a84ff;
}
.rx-disabled{
    background: rgba(245, 246, 249, 1);
    display: flex;
    align-items: center;
    padding: 0.5rem;
    border-radius: 4px;
    border: none;
    min-height: 1rem;
}
</style>
